import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot;
import java.awt.Color;

public class DataManagement extends JFrame {
    private FamilyFinanceManager mainFrame;
    private JButton backButton;

    public DataManagement(FamilyFinanceManager mainFrame) {
        this.mainFrame = mainFrame;
        setTitle("数据图表展示");
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setSize(800, 600);
        setLocationRelativeTo(null);

        // 创建选项卡面板
        JTabbedPane tabbedPane = new JTabbedPane();

        // 添加收入图表
        tabbedPane.addTab("收入", createIncomeChartPanel());

        // 添加支出图表
        tabbedPane.addTab("支出", createExpenseChartPanel());

        // 添加预算图表
        tabbedPane.addTab("预算", createBudgetChartPanel());

        // 添加表格展示
        tabbedPane.addTab("数据表格", createDataTablePanel());

        // 返回按钮
        backButton = new JButton("返回");
        backButton.addActionListener(e -> {
            mainFrame.setVisible(true);
            dispose();
        });

        // 布局
        add(tabbedPane, BorderLayout.CENTER);
        add(backButton, BorderLayout.SOUTH);
    }

    // 创建收入图表面板
    private ChartPanel createIncomeChartPanel() {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        // 获取所有收入条目
        List<String> incomes = DataManager.getIncomes();
        for (String income : incomes) {
            String[] parts = income.split(", ");
            String source = parts[0].replace("来源: ", "");
            double amount = Double.parseDouble(parts[2].replace("金额: ", ""));
            dataset.addValue(amount, "收入", source);
        }

        JFreeChart barChart = ChartFactory.createBarChart(
                "收入分布",
                "收入来源",
                "金额 (元)",
                dataset,
                PlotOrientation.VERTICAL,
                true, true, false);

        // 自定义样式
        CategoryPlot plot = barChart.getCategoryPlot();
        NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
        BarRenderer renderer = (BarRenderer) plot.getRenderer();
        renderer.setSeriesPaint(0, new Color(51, 153, 255)); // 蓝色系

        return new ChartPanel(barChart);
    }

    // 创建支出图表面板
    private ChartPanel createExpenseChartPanel() {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        // 获取所有支出条目
        List<String> expenses = DataManager.getExpenses();
        for (String expense : expenses) {
            String[] parts = expense.split(", ");
            String source = parts[0].replace("来源: ", "");
            double amount = Double.parseDouble(parts[2].replace("金额: ", ""));
            dataset.addValue(amount, "支出", source);
        }

        JFreeChart barChart = ChartFactory.createBarChart(
                "支出分布",
                "支出来源",
                "金额 (元)",
                dataset,
                PlotOrientation.VERTICAL,
                true, true, false);

        // 自定义样式
        CategoryPlot plot = barChart.getCategoryPlot();
        NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
        BarRenderer renderer = (BarRenderer) plot.getRenderer();
        renderer.setSeriesPaint(0, new Color(255, 99, 71)); // 红橙色系

        return new ChartPanel(barChart);
    }

    // 创建预算图表面板
    private ChartPanel createBudgetChartPanel() {
        DefaultPieDataset dataset = new DefaultPieDataset();

        // 获取所有预算条目
        List<String> budgets = DataManager.getBudgets();
        if (!budgets.isEmpty()) {
            String budget = budgets.get(0); // 假设只有一条预算记录
            String[] parts = budget.split(", ");
            String daily = parts[0].replace("日预算: ", "");
            String monthly = parts[1].replace("月预算: ", "");
            String yearly = parts[2].replace("年预算: ", "");

            dataset.setValue("日预算", Double.parseDouble(daily));
            dataset.setValue("月预算", Double.parseDouble(monthly));
            dataset.setValue("年预算", Double.parseDouble(yearly));
        }

        JFreeChart pieChart = ChartFactory.createPieChart(
                "预算分布",
                dataset,
                true,
                true,
                false);

        // 显示百分比标签
        PiePlot piePlot = (PiePlot) pieChart.getPlot();
        piePlot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0} ({2})")); // 显示名称+百分比
        piePlot.setLabelBackgroundPaint(Color.WHITE); // 标签背景色
        piePlot.setOutlinePaint(Color.BLACK); // 边框颜色

        return new ChartPanel(pieChart);
    }

    // 创建数据表格面板
    private JPanel createDataTablePanel() {
        JPanel panel = new JPanel(new BorderLayout());

        // 定义表头
        String[] columnNames = {"类型", "来源", "时间", "金额"};

        // 获取收入和支出数据
        List<String> incomes = DataManager.getIncomes();
        List<String> expenses = DataManager.getExpenses();

        // 创建数据模型
        DefaultTableModel model = new DefaultTableModel(columnNames, 0);

        // 添加收入数据到表格
        for (String income : incomes) {
            String[] parts = income.split(", ");
            String source = parts[0].replace("来源: ", "");
            String time = parts[1].replace("时间: ", "");
            String amount = parts[2].replace("金额: ", "");
            model.addRow(new Object[]{"收入", source, time, amount});
        }

        // 添加支出数据到表格
        for (String expense : expenses) {
            String[] parts = expense.split(", ");
            String source = parts[0].replace("来源: ", "");
            String time = parts[1].replace("时间: ", "");
            String amount = parts[2].replace("金额: ", "");
            model.addRow(new Object[]{"支出", source, time, amount});
        }

        // 创建表格
        JTable table = new JTable(model);

        // 添加表格到滚动面板
        JScrollPane scrollPane = new JScrollPane(table);

        // 将滚动面板添加到面板
        panel.add(scrollPane, BorderLayout.CENTER);

        return panel;
    }
}